/*
 Simple example of making a thread detachable
 */
#include <stdio.h> 
#include <string.h> 
#include <pthread.h>
#include <unistd.h>
#include <limits.h>

#define SLEEP_TIME 10

void * sleepy_thread(void *);


int main(int argc,char *argv[]){
  int error;
  size_t stack_size;
  pthread_attr_t attr;
  pthread_t tid;
  void *return_value;
  
  if ((error = pthread_attr_init(&attr)) != 0)
       fprintf(stderr, "Failed to create attribute object: %s\n",strerror(error));

#ifdef _POSIX_THREAD_ATTR_STACKSIZE
  else if((error = pthread_attr_getstacksize(&attr,&stack_size)) != 0)
       fprintf(stderr, "Failed to get stacksize attribute object: %s\n",strerror(error));
  printf("The default stack size as : %d , The minimum is %d \n",stack_size,PTHREAD_STACK_MIN);
  
  /* Now lets set the stack as twice as MIN ok !*/
  if((error = pthread_attr_setstacksize(&attr,PTHREAD_STACK_MIN*2)) != 0)
       fprintf(stderr, "Failed to set stacksize attribute object: %s\n",strerror(error));
 
#endif

  if ((error = pthread_create(&tid, &attr, sleepy_thread, (void*)SLEEP_TIME)) != 0)
       fprintf(stderr, "Failed to create thread: %s\n", strerror(error));
  
  
  printf("Waiting for thread to finish ...\n");
  if((error=pthread_join(tid,&return_value)) != 0){
    fprintf(stderr, "Failed to join the thread:\n");
  }
   

  return 0;
}

void * sleepy_thread(void *arg){
  
  printf("Sleeping Thread ...\n");
  sleep((int)arg);
  printf("End of Sleep ...\n");

  return (void *)0;
}

